//
//  KDWeiboSetController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/3.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDWeiboSetController.h"
#import "GBWeiboMonitorNameViewController.h"
#import "GBWeiboKeywordViewController.h"
#import "AFNetworking.h"
#import "KDMSettingCellModel.h"
@interface KDWeiboSetController ()<UITextFieldDelegate, WeiboReturnMonitorTitle, WeiboReturnTheKeyword>
{
    UIButton *shareBtn; //单位共享的btn
    UIButton *saveButton; //保存按钮
    NSMutableArray *weiboArray; //微博关键词的数组
    
    //11.8
    UILabel *monitorNameLabel; //监测名称label
    UILabel *monitorNameSelectLabel; //监测名称选择的label
    UILabel *weiboKeywordLabel; //微博关键词label
    UILabel *weiboKeywordSelectLabel; //微博关键词选择label
    NSString *titleString; //监测名称的string
}
@end

@implementation KDWeiboSetController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WQColor(247, 249, 250);
    
    //创建主界面
    [self createMainView];
    
    //创建保存按钮
    [self createSaveBtn];
    // Do any additional setup after loading the view.
}

#pragma mark - 创建主界面
-(void)createMainView
{
    //创建监测名称界面
    [self createMonitorView];
    
    //创建微博关键词界面
    [self createWeiboKeywordView];
}

#pragma mark - 创建监测名称界面
-(void)createMonitorView
{
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 20, screenW, 40)];
    view1.backgroundColor = [UIColor whiteColor];
    
    monitorNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, screenW - 85, 40)];
    monitorNameLabel.text = @"监测名称";
    monitorNameLabel.textAlignment = NSTextAlignmentLeft;
    
    monitorNameSelectLabel = [[UILabel alloc] initWithFrame:CGRectMake(screenW - 80, 0, 40, 40)];
    monitorNameSelectLabel.text = @"未选择";
    monitorNameSelectLabel.font = [UIFont systemFontOfSize:12];
    monitorNameSelectLabel.textColor = [UIColor lightGrayColor];
    monitorNameSelectLabel.textAlignment = NSTextAlignmentCenter;
    
    UIImageView *arrawImageview = [[UIImageView alloc] initWithFrame:CGRectMake(screenW - 40, 0, 40, 40)];
    arrawImageview.image = [UIImage imageNamed:@"rightArraw"];
    
    UIButton *nameBtn = [UIButton buttonWithType:0];
    nameBtn.frame = CGRectMake(0, 0, screenW, 40);
    nameBtn.backgroundColor = [UIColor clearColor];
    [nameBtn addTarget:self action:@selector(GotoNameSelect) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, screenW, 25)];
    hintLabel.backgroundColor = WQColor(247, 249, 250);
    hintLabel.font = [UIFont systemFontOfSize:12];
    hintLabel.textColor = [UIColor lightGrayColor];
    hintLabel.text = @"输入微博监测名称。请点击进去输入。";
    
    shareBtn = [UIButton buttonWithType:0];
    shareBtn.frame = CGRectMake(10, 90, 20, 20);
    shareBtn.backgroundColor = [UIColor whiteColor];
    [shareBtn setImage:[UIImage imageNamed:@"check_normal"] forState:UIControlStateNormal];
    [shareBtn setImage:[UIImage imageNamed:@"check_checked"] forState:UIControlStateSelected];
    [shareBtn addTarget:self action:@selector(ShareSelectAction) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(40, 85, 60, 30)];
    titleLab.text = @"单位可见";
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.font = [UIFont systemFontOfSize:12];
    titleLab.textColor = [UIColor lightGrayColor];
    titleLab.backgroundColor = WQColor(247, 249, 250);
    
    [self.view addSubview:view1];
    [view1 addSubview:monitorNameLabel];
    [view1 addSubview:monitorNameSelectLabel];
    [view1 addSubview:arrawImageview];
    [view1 addSubview:nameBtn];
    [self.view addSubview:hintLabel];
    [self.view addSubview:shareBtn];
    [self.view addSubview:titleLab];
}

#pragma mark - 单位可见按钮的操作
-(void)ShareSelectAction
{
    shareBtn.selected = !shareBtn.selected;
}

#pragma mark - 创建微博关键词界面
-(void)createWeiboKeywordView
{
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 115, screenW, 40)];
    view1.backgroundColor = [UIColor whiteColor];
    
    weiboKeywordLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, screenW - 85, 40)];
    weiboKeywordLabel.text = @"微博关键词";
    weiboKeywordLabel.textAlignment = NSTextAlignmentLeft;
    
    weiboKeywordSelectLabel = [[UILabel alloc] initWithFrame:CGRectMake(screenW - 80, 0, 40, 40)];
    weiboKeywordSelectLabel.text = @"未选择";
    weiboKeywordSelectLabel.font = [UIFont systemFontOfSize:12];
    weiboKeywordSelectLabel.textColor = [UIColor lightGrayColor];
    weiboKeywordSelectLabel.textAlignment = NSTextAlignmentCenter;
    
    UIImageView *arrawImageview = [[UIImageView alloc] initWithFrame:CGRectMake(screenW - 40, 0, 40, 40)];
    arrawImageview.image = [UIImage imageNamed:@"rightArraw"];
    
    UIButton *nameBtn = [UIButton buttonWithType:0];
    nameBtn.frame = CGRectMake(0, 0, screenW, 40);
    nameBtn.backgroundColor = [UIColor clearColor];
    [nameBtn addTarget:self action:@selector(GotoWeiboKeywordSelect) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 155, screenW, 25)];
    hintLabel.backgroundColor = WQColor(247, 249, 250);
    hintLabel.font = [UIFont systemFontOfSize:12];
    hintLabel.textColor = [UIColor lightGrayColor];
    hintLabel.text = @"输入微博关键词，筛选区域用途。";
    
    [self.view addSubview:view1];
    [view1 addSubview:weiboKeywordLabel];
    [view1 addSubview:weiboKeywordSelectLabel];
    [view1 addSubview:arrawImageview];
    [view1 addSubview:nameBtn];
    [self.view addSubview:hintLabel];
}

#pragma mark - 跳转监测名称界面
-(void)GotoNameSelect
{
    GBWeiboMonitorNameViewController *monitorName = [[GBWeiboMonitorNameViewController alloc] init];
    monitorName.delegateWeiboMonitorTitle = self;
    //monitorName.titleAuthorName = @"斌哥真帅！";
    [self.navigationController pushViewController:monitorName animated:YES];
}

#pragma mark - 返回监测名称的代理
-(void)weiboReturnMonitorTitle:(NSString *)title
{
    titleString = [NSString stringWithFormat:@"%@", title];
}

#pragma mark - 跳转监测名称界面
-(void)GotoWeiboKeywordSelect
{
    GBWeiboKeywordViewController *weiboKeyword = [[GBWeiboKeywordViewController alloc] init];
    weiboKeyword.delegateWeiboKeyword = self;
    
//    NSMutableArray *ar = [NSMutableArray array];
//    for(int i = 0; i < 3; i++)
//    {
//        [ar addObject:[NSString stringWithFormat:@"斌哥好帅%d", i]];
//    }
//    weiboKeyword.dataArray = [NSMutableArray arrayWithArray:ar];
    [self.navigationController pushViewController:weiboKeyword animated:YES];
}

#pragma mark - 返回微博关键字的代理
-(void)weiboReturnTheKeyword:(NSMutableArray *)array
{
    weiboArray = [NSMutableArray arrayWithArray:array];
}

#pragma mark - 创建保存按钮
-(void)createSaveBtn
{
    saveButton = [UIButton buttonWithType:0];
    saveButton.frame = CGRectMake(10, 200, screenW - 20, 35);
    saveButton.layer.cornerRadius = 5;
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    saveButton.backgroundColor = KDColor;
    [saveButton addTarget:self action:@selector(SaveTheData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];     
}

#pragma mark - 保存按钮点击操作
-(void)SaveTheData
{
    KDLog(@"2%@", titleString);
    KDLog(@"3%@", weiboArray);
    
    NSString *selectY = nil;
    if(shareBtn.isSelected)
    {
        selectY = @"1";
    }
    else
    {
        selectY = @"0";
    }
   
    NSString *weiboKeywordString = [NSString stringWithFormat:@"%@", weiboArray[0]];
    for(int i = 1; i < weiboArray.count; i++)
    {
        weiboKeywordString = [NSString stringWithFormat:@"%@", weiboArray[1]];
    }
    
    KDAccount *account = [KDAccountTool account];
    NSString *saveUrl = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@", ServerActionAddr, @"&method=weiboMonitorEdit&token=",account.tokens,@"&W_Name=",titleString,@"&W_Share=",selectY,@"&keyword=",weiboKeywordString];
    KDLog(@"%@",saveUrl);
        //请求数据
        NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:saveUrl]];
    
        AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
        [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
            NSHTTPURLResponse *response = [op response];
            NSInteger code = [response statusCode];
            if (code == 200)
            {
                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
                if([jsonDict[@"status"] isEqualToString:@"ok"])
                {
                    NSString *_message = @"保存成功";
                    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
                    [NSTimer scheduledTimerWithTimeInterval:1.8f
                                                     target:self
                                                   selector:@selector(timerFireMethod:)
                                                   userInfo:promptAlert
                                                    repeats:YES];
                    [promptAlert show];
    
                    [self.navigationController popViewControllerAnimated:YES];
                }
                //账号在别处登录
                else if([jsonDict[@"status"] isEqualToString:@"notlogin"])
                {
                    NSString *_message = @"该账号已在其他地方登陆";
                    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
                    [NSTimer scheduledTimerWithTimeInterval:1.8f
                                                     target:self
                                                   selector:@selector(timerFireMethod:)
                                                   userInfo:promptAlert
                                                    repeats:YES];
                    [promptAlert show];
    
                    KDNewfeatureController *login = [[KDNewfeatureController alloc] init];
                    //跳转到登陆界面
                    //设置切换风格
                    login.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                    //2.切换控制器
                    [self presentViewController:login animated:YES completion:nil];
                }
                //保存失败
                else if ([jsonDict[@"status"] isEqualToString:@"err"])
                {
                    NSString *_message = @"保存失败";
                    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
                    [NSTimer scheduledTimerWithTimeInterval:1.8f
                                                     target:self
                                                   selector:@selector(timerFireMethod:)
                                                   userInfo:promptAlert
                                                    repeats:YES];
                    [promptAlert show];
                }
            }
        } failure:^(AFHTTPRequestOperation *op, NSError *error) {
            if (error) {
                KDLog(@"req error %@",error);
            }
        }];
        [reqOper start];
}

#pragma mark - 弹出的对话框内容
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert = nil;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    if(titleString == nil || [titleString isEqualToString:@""])
    {
        monitorNameLabel.text = @"监测名称";
        monitorNameSelectLabel.text = @"未选择";
    }
    else
    {
        monitorNameLabel.text = titleString;
        monitorNameSelectLabel.text = @"已选择";
    }
    
    if(weiboArray.count == 0)
    {
        weiboKeywordLabel.text = @"微博关键词";
        weiboKeywordSelectLabel.text = @"未选择";
    }
    else
    {
        weiboKeywordLabel.text = [NSString stringWithFormat:@"%@", weiboArray[0]];
        weiboKeywordSelectLabel.text = @"已选择";
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
